<script setup lang="ts">
import {ref, onMounted, watch, nextTick} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import {useExamResultStore} from '../stores/examResult'
import {ElContainer, ElAside, ElMain, ElHeader, ElScrollbar, ElButton, ElTabs, ElTabPane, ElAlert} from 'element-plus'

// ==================== 数据定义 ====================
const route = useRoute()
const router = useRouter()
const examResultStore = useExamResultStore()

// 获取题目数量参数和模式参数
const examMode = route.query.mode || 'exam' // 默认为考试模式
const chapter = Number(route.query.chapter) || 1 // 章节号（1-8）
const isReadOnly = ref(route.query.readOnly === 'true') // 只读模式开关

// 考试时间相关
const examStartTime = ref<number>(0) // 考试开始时间戳

// 答案数据
const singleAnswer = ref('')
const multipleAnswers = ref([])
const trueFalseAnswer = ref('')

// 创建题目列表
const questions = ref([])
const currentQuestionId = ref(1) // 默认显示第一题
const activeTab = ref('single') // 默认激活的标签页
const examData = ref(null) // 存储从JSON文件加载的考试数据
const showHint = ref(false) // 控制提示信息显示状态

// 生成唯一的考试会话ID
const examSessionId = ref('')

// ==================== 题目数量配置 ====================
// 根据模式设置默认题目数量
const getDefaultQuestionCounts = () => {
  if (examMode === 'exam') {
    // 考试模式：单选题140道，多选题10道，判断题40道
    return { single: 140, multiple: 10, trueFalse: 40 };
  } else if (examMode === 'practice' && route.query.practiceMode === 'random') {
    // 随机练习模式：单选题38道，多选题38道，判断题38道
    return { single: 38, multiple: 38, trueFalse: 38 };
  } else if (examMode === 'practice' && route.query.practiceMode === 'chapter') {
    // 章节练习模式：使用章节题库中的所有题目（暂时设置为默认值）
    return { single: 50, multiple: 50, trueFalse: 50 };
  } else if (examMode === 'practice' && route.query.practiceMode === 'wrong') {
    // 错题库练习模式：单选题40道，多选题40道，判断题40道
    return { single: 40, multiple: 40, trueFalse: 40 };
  } else {
    // 练习模式默认值（如果没有指定practiceMode）
    return { single: 38, multiple: 38, trueFalse: 38 };
  }
}

const { single: defaultSingle, multiple: defaultMultiple, trueFalse: defaultTrueFalse } = getDefaultQuestionCounts();

// 获取题目数量参数，如果没有指定则使用默认值
const singleCount = Number(route.query.single) || defaultSingle
const multipleCount = Number(route.query.multiple) || defaultMultiple
const trueFalseCount = Number(route.query.trueFalse) || defaultTrueFalse


// ==================== 工具方法 ====================
/**
 * Fisher-Yates 随机算法
 */
const shuffleArray = (array) => {
  const newArray = [...array]
  for (let i = newArray.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [newArray[i], newArray[j]] = [newArray[j], newArray[i]]
  }
  return newArray
}

// ==================== 数据存储 ====================
/**
 * 保存考试信息到localStorage
 */
const saveExamInfo = () => {
  let examType = 'exam'; // 默认为考试模式
  let practiceMode = null;
  let chapterInfo = null;
  let examId = null; // 用于随机练习的唯一标识

  if (examMode === 'practice') {
    if (route.query.practiceMode === 'chapter') {
      examType = 'chapter';
      practiceMode = 'chapter';
      chapterInfo = chapter;
    } else if (route.query.practiceMode === 'random') {
      examType = 'random';
      practiceMode = 'random';
      // 为随机练习生成唯一ID
      examId = `random_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    } else if (route.query.practiceMode === 'wrong') {
      examType = 'wrong';
      practiceMode = 'wrong';
    } else {
      // 如果是练习模式但没有指定具体的练习类型，默认为随机练习
      examType = 'random';
      practiceMode = 'random';
      examId = `random_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    }
  }

  const examInfo = {
    examType: examType,
    chapter: chapterInfo,
    practiceMode: practiceMode,
    examId: examId, // 用于随机练习的唯一标识
    timestamp: Date.now() // 添加时间戳用于清理过期数据
  }

  localStorage.setItem('currentExamInfo', JSON.stringify(examInfo));

  // 如果是随机练习，还需要保存题目到localStorage
  if (examType === 'random' && examId && questions.value.length > 0) {
    const randomExamData = {
      examId: examId,
      timestamp: Date.now(),
      questions: questions.value.map(q => ({
        id: q.id,
        number: q.number,
        type: q.type,
        typeName: q.typeName,
        title: q.title,
        content: q.content,
        options: q.options,
        originalId: q.originalId,
        analysis: q.analysis
      }))
    };

    localStorage.setItem(`randomExam_${examId}`, JSON.stringify(randomExamData));
  }
}

// ==================== 题库加载 ====================
/**
 * 从JSON文件加载题目数据
 */
const loadExamData = async () => {
  try {
    let responseFile = '';

    // 在只读模式下，根据路由参数加载对应的题库
    if (isReadOnly.value) {
      // 根据路由参数确定考试类型
      const examType = route.query.mode === 'exam' ? 'exam' :
          route.query.practiceMode === 'chapter' ? 'chapter' :
              route.query.practiceMode === 'random' ? 'random' : 'exam';

      if (examType === 'chapter') {
        // 章节练习模式，根据章节号加载对应的题库
        const chapter = Number(route.query.chapter) || 1;
        responseFile = `/questionBank/response-${chapter}.json`;
      } else if (examType === 'random') {
        // 随机练习模式，直接从localStorage加载题目
        // 由于在ResultPage.vue中已经更新了localStorage中的题目数据，这里直接加载即可
        const examInfoStr = localStorage.getItem('currentExamInfo');
        if (examInfoStr) {
          const examInfo = JSON.parse(examInfoStr);
          if (examInfo.examId) {
            const randomExamDataStr = localStorage.getItem(`randomExam_${examInfo.examId}`);
            if (randomExamDataStr) {
              const randomExamData = JSON.parse(randomExamDataStr);
              // 直接使用已保存的题目
              questions.value = randomExamData.questions.map(q => ({
                ...q,
                answered: q.answered || false,
                userAnswer: q.userAnswer || ''
              }));

              // 恢复答题记录
              restoreAnswerRecords();
              return;
            } else {
              // 如果找不到保存的题目，则使用默认题库
              responseFile = '/questionBank/response-0.json';
            }
          } else {
            responseFile = '/questionBank/response-0.json';
          }
        } else {
          responseFile = '/questionBank/response-0.json';
        }
      } else {
        // 考试模式，使用response-test.json作为题库
        responseFile = '/questionBank/response-test.json';
      }
    } else {
      // 非只读模式下保持原有逻辑
      if (examMode === 'practice' && route.query.practiceMode === 'chapter') {
        // 章节练习模式，根据章节号加载对应的题库
        responseFile = `/questionBank/response-${chapter}.json`;
      } else if (examMode === 'practice' && route.query.practiceMode === 'wrong') {
        // 错题库练习模式，从历史记录中加载错题
        await loadWrongQuestions();
        return;
      } else if (examMode === 'practice' && route.query.practiceMode === 'random') {
        // 随机练习模式，使用response-0.json作为题库
        responseFile = '/questionBank/response-0.json';
      } else {
        // 考试模式，使用response-test.json作为题库
        responseFile = '/questionBank/response-test.json';
      }
    }

    // 加载对应的题库文件
    const response = await fetch(responseFile)
    const data = await response.json()
    examData.value = data

    // 生成题目数据
    generateQuestionsFromData(data)
  } catch (error) {
    console.error('加载考试数据失败:', error)
    // 如果加载失败，使用原来的模拟数据
    questions.value = generateMockQuestions()
  }
}

/**
 * 根据JSON数据生成题目列表
 */
const generateQuestionsFromData = (data) => {
  const questionList = []
  const paper = data.paper

  if (paper && paper.questions) {
    // 在只读模式下、章节练习模式下或考试模式下，直接使用所有题目（按顺序）
    if (isReadOnly.value || (examMode === 'practice' && route.query.practiceMode === 'chapter') || examMode === 'exam') {
      // 考试模式或章节练习模式或只读模式，直接按顺序使用题目
      const selectedQuestions = [...paper.questions];

      // 如果是考试模式，按题目类型分类并按顺序抽取
      if (examMode === 'exam') {
        // 按题目类型分类
        const singleQuestions = [];
        const multipleQuestions = [];
        const trueFalseQuestions = [];

        paper.questions.forEach((questionData) => {
          switch (questionData.type) {
            case 1: // 单选题
              singleQuestions.push(questionData);
              break;
            case 2: // 多选题
              multipleQuestions.push(questionData);
              break;
            case 3: // 判断题
              trueFalseQuestions.push(questionData);
              break;
          }
        });

        // 按顺序抽取指定数量的题目
        const selectedSingle = singleQuestions.slice(0, singleCount);
        const selectedMultiple = multipleQuestions.slice(0, multipleCount);
        const selectedTrueFalse = trueFalseQuestions.slice(0, trueFalseCount);

        // 合并所有选中的题目
        selectedQuestions.splice(0, selectedQuestions.length, ...selectedSingle, ...selectedMultiple, ...selectedTrueFalse);
      }

      // 构造题目对象
      selectedQuestions.forEach((questionData, index) => {
        // 确定题目类型 (1:单选题, 2:多选题, 3:判断题)
        let type = 0;
        let typeName = '';
        switch (questionData.type) {
          case 1:
            type = 1;
            typeName = '单选题';
            break;
          case 2:
            type = 2;
            typeName = '多选题';
            break;
          case 3:
            type = 3;
            typeName = '判断题';
            break;
        }

        // 构造选项列表
        let options = [];
        if (questionData.type === 3) {
          // 判断题特殊处理：固定两个选项（正确/错误）
          options = [
            {
              label: 'A',
              text: '正确',
              value: '1',
              name: '1',
              isCorrect: questionData.questionAttrCopys.find(attr => attr.name === '0')?.value === '1'
            },
            {
              label: 'B',
              text: '错误',
              value: '0',
              name: '0',
              isCorrect: questionData.questionAttrCopys.find(attr => attr.name === '0')?.value === '0'
            }
          ];
        } else {
          // 单选题和多选题正常处理
          options = questionData.questionAttrCopys.map(attr => ({
            label: String.fromCharCode(65 + parseInt(attr.name)), // 将0,1,2,3转换为A,B,C,D
            text: attr.value,
            id: attr.id,
            name: attr.name, // 保存原始name用于排序
            isCorrect: attr.type === '0' // 0表示正确答案，1表示错误答案
          }))

          // 对选项进行排序
          options.sort((a, b) => parseInt(a.name) - parseInt(b.name));
        }

        questionList.push({
          id: index + 1,
          number: index + 1,
          type: type,
          typeName: typeName,
          title: `${typeName} ${index + 1}`,
          content: questionData.content,
          options: options,
          answered: false,
          userAnswer: '', // 用户答案
          originalId: questionData.id, // 原始题目ID
          answerRecord: questionData.answerRecord, // 答案记录
          analysis: questionData.parsingText || '' // 添加答案解析属性
        });
      });
    } else {
      // 随机练习模式，按题目类型分类并随机抽取
      const singleQuestions = [];
      const multipleQuestions = [];
      const trueFalseQuestions = [];

      paper.questions.forEach((questionData) => {
        switch (questionData.type) {
          case 1: // 单选题
            singleQuestions.push(questionData);
            break;
          case 2: // 多选题
            multipleQuestions.push(questionData);
            break;
          case 3: // 判断题
            trueFalseQuestions.push(questionData);
            break;
        }
      });

      // 随机打乱各类型题目
      const shuffledSingle = shuffleArray(singleQuestions);
      const shuffledMultiple = shuffleArray(multipleQuestions);
      const shuffledTrueFalse = shuffleArray(trueFalseQuestions);

      // 按指定数量抽取题目
      const selectedSingle = shuffledSingle.slice(0, singleCount);
      const selectedMultiple = shuffledMultiple.slice(0, multipleCount);
      const selectedTrueFalse = shuffledTrueFalse.slice(0, trueFalseCount);

      // 合并所有选中的题目
      const selectedQuestions = [...selectedSingle, ...selectedMultiple, ...selectedTrueFalse];

      // 重新编号并构造题目对象
      selectedQuestions.forEach((questionData, index) => {
        // 确定题目类型 (1:单选题, 2:多选题, 3:判断题)
        let type = 0;
        let typeName = '';
        switch (questionData.type) {
          case 1:
            type = 1;
            typeName = '单选题';
            break;
          case 2:
            type = 2;
            typeName = '多选题';
            break;
          case 3:
            type = 3;
            typeName = '判断题';
            break;
        }

        // 构造选项列表
        let options = [];
        if (questionData.type === 3) {
          // 判断题特殊处理：固定两个选项（正确/错误）
          options = [
            {
              label: 'A',
              text: '正确',
              value: '1',
              name: '1',
              isCorrect: questionData.questionAttrCopys.find(attr => attr.name === '0')?.value === '1'
            },
            {
              label: 'B',
              text: '错误',
              value: '0',
              name: '0',
              isCorrect: questionData.questionAttrCopys.find(attr => attr.name === '0')?.value === '0'
            }
          ];
        } else {
          // 单选题和多选题正常处理
          options = questionData.questionAttrCopys.map(attr => ({
            label: String.fromCharCode(65 + parseInt(attr.name)), // 将0,1,2,3转换为A,B,C,D
            text: attr.value,
            id: attr.id,
            name: attr.name, // 保存原始name用于排序
            isCorrect: attr.type === '0' // 0表示正确答案，1表示错误答案
          }))

          // 对选项进行排序
          options.sort((a, b) => parseInt(a.name) - parseInt(b.name));
        }

        questionList.push({
          id: index + 1,
          number: index + 1,
          type: type,
          typeName: typeName,
          title: `${typeName} ${index + 1}`,
          content: questionData.content,
          options: options,
          answered: false,
          userAnswer: '', // 用户答案
          originalId: questionData.id, // 原始题目ID
          answerRecord: questionData.answerRecord, // 答案记录
          analysis: questionData.parsingText || '' // 添加答案解析属性
        });
      });
    }
  }

  questions.value = questionList

  // 恢复答题记录
  restoreAnswerRecords()
}

/**
 * 从历史记录中加载错题
 */
const loadWrongQuestions = async () => {
  try {
    // 获取历史记录
    const historyStr = localStorage.getItem('examHistory');
    if (!historyStr) {
      console.warn('没有找到历史记录');
      // 如果没有历史记录，使用默认题库
      loadDefaultQuestions();
      return;
    }

    const examHistory = JSON.parse(historyStr);
    if (!examHistory || examHistory.length === 0) {
      console.warn('历史记录为空');
      // 如果历史记录为空，使用默认题库
      loadDefaultQuestions();
      return;
    }

    // 获取当前考试类型信息
    const currentExamInfoStr = localStorage.getItem('currentExamInfo');
    let currentExamInfo = {};
    if (currentExamInfoStr) {
      try {
        currentExamInfo = JSON.parse(currentExamInfoStr);
      } catch (e) {
        console.error('解析当前考试信息失败:', e);
      }
    }

    // 收集所有错题和未答题
    let wrongQuestions = [];

    // 遍历所有历史记录
    for (const record of examHistory) {
      // 对于章节练习，检查章节是否匹配
      let examType = record.examType
      let chapter = record.chapter
      let examId =record.examId
      let questionBank = [];
      if ( chapter && record.chapter !== chapter) {
        console.log('跳过不匹配的章节')
        return; // 跳过不匹配的章节
      }
      if (examType === 'random' && examId) {
        // 随机练习从localStorage加载题库
        const randomExamDataStr = localStorage.getItem(`randomExam_${examId}`);
        if (randomExamDataStr) {
          try {
            const randomExamData = JSON.parse(randomExamDataStr);
            questionBank = randomExamData.questions;
          } catch (e) {
            console.error('解析随机练习题库失败:', e);
          }
        }
      } else if (examType === 'chapter' && chapter) {
        // 章节练习从对应章节题库加载
        try {
          const response = await fetch(`/questionBank/response-${chapter}.json`);
          const data = await response.json();
          questionBank = data.paper.questions
        } catch (e) {
          console.error(`加载章节${chapter}题库失败:`, e);
        }
      } else if (examType === 'exam') {
        // 正式考试从考试题库加载
        try {
          const response = await fetch('/questionBank/response-test.json');
          const data = await response.json();
          questionBank = data.paper.questions
        } catch (e) {
          console.error('加载正式考试题库失败:', e);
        }
      } else {
        // 默认从题库0加载
        try {
          const response = await fetch('/questionBank/response-0.json');
          const data = await response.json();
          questionBank = data.paper.questions
        } catch (e) {
          console.error('加载默认题库失败:', e);
        }
      }
      wrongQuestions =[...wrongQuestions,  ...questionBank.filter((question, index) => {
            question.userAnswer = record.questions[index].answered
            question.answered = record.questions[index].answered
            question.isCorrect = record.questions[index].isCorrect
        return !record.questions[index].isCorrect
      })]
      console.log(22, wrongQuestions)
    }
    console.log(111, wrongQuestions)
    if (wrongQuestions.length === 0) {
      console.warn('没有找到错题');
      // 如果没有错题，使用默认题库
      loadDefaultQuestions();
      return;
    }

    // 匹配错题和题库中的题目
    const matchedQuestions = [];
    wrongQuestions.forEach(wrongQuestion => {
      // 在题库中查找对应的题目
      const matchedQuestion = wrongQuestion

      if (matchedQuestion) {
        // 构造题目选项
        let options = [];
        if (matchedQuestion.type === 3) {
          // 判断题特殊处理
          options = [
            {
              label: 'A',
              text: '正确',
              value: '1',
              name: '1',
              isCorrect: matchedQuestion.questionAttrCopys.find(attr => attr.name === '0')?.value === '1'
            },
            {
              label: 'B',
              text: '错误',
              value: '0',
              name: '0',
              isCorrect: matchedQuestion.questionAttrCopys.find(attr => attr.name === '0')?.value === '0'
            }
          ];
        } else {
          // 其他题型处理
          options = matchedQuestion.questionAttrCopys.map(attr => ({
            label: String.fromCharCode(65 + parseInt(attr.name)), // 将0,1,2,3转换为A,B,C,D
            text: attr.value,
            id: attr.id,
            name: attr.name, // 保存原始name用于排序
            isCorrect: attr.type === '0' // 0表示正确答案，1表示错误答案
          }));

          // 对选项进行排序
          options.sort((a, b) => parseInt(a.name) - parseInt(b.name));
        }

        matchedQuestions.push({
          ...matchedQuestion,
          typeName: wrongQuestion.typeName,
          options: options,
          parsingText: matchedQuestion.parsingText || ''
        });
      }
    });

    // 按题目类型分类
    const singleQuestions = matchedQuestions.filter(q => q.type === 1);
    const multipleQuestions = matchedQuestions.filter(q => q.type === 2);
    const trueFalseQuestions = matchedQuestions.filter(q => q.type === 3);

    // 随机打乱各类型题目
    const shuffledSingle = shuffleArray(singleQuestions);
    const shuffledMultiple = shuffleArray(multipleQuestions);
    const shuffledTrueFalse = shuffleArray(trueFalseQuestions);

    // 按指定数量抽取题目（最多40题）
    const selectedSingle = shuffledSingle.slice(0, singleCount);
    const selectedMultiple = shuffledMultiple.slice(0, multipleCount);
    const selectedTrueFalse = shuffledTrueFalse.slice(0, trueFalseCount);

    // 合并所有选中的题目
    const selectedQuestions = [...selectedSingle, ...selectedMultiple, ...selectedTrueFalse];

    // 构造题目数据
    const questionList = [];
    selectedQuestions.forEach((questionData, index) => {
      // 确定题目类型
      let type = questionData.type;
      let typeName = questionData.typeName;
      
      if (!typeName) {
        switch (type) {
          case 1:
            typeName = '单选题';
            break;
          case 2:
            typeName = '多选题';
            break;
          case 3:
            typeName = '判断题';
            break;
          default:
            typeName = '单选题';
        }
      }

      questionList.push({
        id: index + 1,
        number: index + 1,
        type: type,
        typeName: typeName,
        title: `${typeName} ${index + 1}`,
        content: questionData.content,
        options: questionData.options,
        answered: false,
        userAnswer: '',
        analysis: questionData.parsingText || ''
      });
    });

    questions.value = questionList;
    restoreAnswerRecords();
  } catch (error) {
    console.error('加载错题失败:', error);
    // 如果加载失败，使用默认题库
    loadDefaultQuestions();
  }
};

/**
 * 加载默认题库
 */
const loadDefaultQuestions = async () => {
  try {
    const response = await fetch('/questionBank/response-0.json');
    const data = await response.json();
    examData.value = data;
    generateQuestionsFromData(data);
  } catch (error) {
    console.error('加载默认题库失败:', error);
    questions.value = generateMockQuestions();
  }
};

/**
 * 模拟题目数据（备用方案）
 */
const generateMockQuestions = () => {
  const mockQuestions = []

  // 生成单选题
  for (let i = 1; i <= singleCount; i++) {
    mockQuestions.push({
      id: i,
      number: i,
      type: 1,
      typeName: '单选题',
      title: `单选题 ${i}`,
      content: `这是一道单选题的题干内容，第${i}题。请仔细阅读题目并选择唯一正确的答案。`,
      options: [
        {label: 'A', text: '选项A的内容描述', isCorrect: true},
        {label: 'B', text: '选项B的内容描述', isCorrect: false},
        {label: 'C', text: '选项C的内容描述', isCorrect: false},
        {label: 'D', text: '选项D的内容描述', isCorrect: false}
      ],
      answered: false,
      userAnswer: '', // 用户答案
      analysis: '这是单选题的答案解析' // 添加答案解析属性
    })
  }

  // 生成多选题
  for (let i = 1; i <= multipleCount; i++) {
    const id = singleCount + i
    mockQuestions.push({
      id: id,
      number: id,
      type: 2,
      typeName: '多选题',
      title: `多选题 ${i}`,
      content: `这是一道多选题的题干内容，第${i}题。请仔细阅读题目并选择所有正确的答案。`,
      options: [
        {label: 'A', text: '选项A的内容描述', isCorrect: true},
        {label: 'B', text: '选项B的内容描述', isCorrect: false},
        {label: 'C', text: '选项C的内容描述', isCorrect: true},
        {label: 'D', text: '选项D的内容描述', isCorrect: false}
      ],
      answered: false,
      userAnswer: [], // 用户答案
      analysis: '这是多选题的答案解析' // 添加答案解析属性
    })
  }

  // 生成判断题
  for (let i = 1; i <= trueFalseCount; i++) {
    const id = singleCount + multipleCount + i
    mockQuestions.push({
      id: id,
      number: id,
      type: 3,
      typeName: '判断题',
      title: `判断题 ${i}`,
      content: `这是一道判断题的题干内容，第${i}题。请判断以下陈述是否正确。`,
      options: [
        {label: 'A', text: '正确', value: '1', isCorrect: true},
        {label: 'B', text: '错误', value: '0', isCorrect: false}
      ],
      answered: false,
      userAnswer: '', // 用户答案
      analysis: '这是判断题的答案解析' // 添加答案解析属性
    })
  }

  return mockQuestions
}

// ==================== 生命周期钩子 ====================
/**
 * 初始化题目数据
 */
onMounted(() => {
  // 只在非只读模式下生成唯一的考试会话ID
  if (!isReadOnly.value) {
    examSessionId.value = `exam_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
  }

  // 记录考试开始时间
  examStartTime.value = Date.now()

  // 只在非只读模式下保存考试信息
  if (!isReadOnly.value) {
    saveExamInfo()
  }

  // 从JSON文件加载数据
  loadExamData()
})


// ==================== 答题处理 ====================
/**
 * 监听答案变化，自动标记为已答
 */
watch(singleAnswer, (newVal) => {
  // 只在非只读模式下处理
  if (!isReadOnly.value && newVal) {
    markAsAnswered(currentQuestionId.value)
    // 保存用户答案
    const question = questions.value.find(q => q.id === currentQuestionId.value)
    if (question) {
      question.userAnswer = newVal
    }

    // 保存答题记录到本地存储
    saveAnswerRecord()
  }
})

watch(multipleAnswers, (newVal) => {
  // 只在非只读模式下处理
  if (!isReadOnly.value && newVal) {
    markAsAnswered(currentQuestionId.value)
    // 保存用户答案
    const question = questions.value.find(q => q.id === currentQuestionId.value)
    if (question) {
      // 确保保存的是数组的副本，而不是引用
      question.userAnswer = [...newVal]
    }

    // 保存答题记录到本地存储
    saveAnswerRecord()
  }
})

watch(trueFalseAnswer, (newVal) => {
  // 只在非只读模式下处理
  if (!isReadOnly.value && newVal) {
    markAsAnswered(currentQuestionId.value)
    // 保存用户答案
    const question = questions.value.find(q => q.id === currentQuestionId.value)
    if (question) {
      question.userAnswer = newVal
    }

    // 保存答题记录到本地存储
    saveAnswerRecord()
  }
})

/**
 * 切换题目
 */
const switchQuestion = (questionId) => {
  currentQuestionId.value = questionId
  showHint.value = false // 切换题目时隐藏提示

  // 清除之前的选择，确保选项处于未选中状态
  const question = questions.value.find(q => q.id === questionId)
  if (question) {
    if (question.type === 1) {
      singleAnswer.value = question.userAnswer || ''
    } else if (question.type === 2) {
      // 对于多选题，确保multipleAnswers是一个数组
      if (Array.isArray(question.userAnswer)) {
        multipleAnswers.value = [...question.userAnswer]
      } else if (typeof question.userAnswer === 'string' && question.userAnswer) {
        // 如果是字符串形式的答案（如"A;B"），需要分割成数组
        multipleAnswers.value = question.userAnswer.split(';').map(ans => ans.trim()).filter(ans => ans)
      } else {
        multipleAnswers.value = []
      }
    } else if (question.type === 3) {
      // 对于判断题，需要将"A"/"B"转换为"1"/"0"
      if (question.userAnswer === 'A') {
        trueFalseAnswer.value = '1'
      } else if (question.userAnswer === 'B') {
        trueFalseAnswer.value = '0'
      } else {
        trueFalseAnswer.value = question.userAnswer !== undefined && question.userAnswer !== null ?
            String(question.userAnswer) : ''
      }
    }
  }
}

/**
 * 获取当前题目
 */
const currentQuestion = () => {
  return questions.value.find(q => q.id === currentQuestionId.value)
}

/**
 * 跳转到上一题
 */
const goToPreviousQuestion = () => {
  if (currentQuestionId.value > 1) {
    switchQuestion(currentQuestionId.value - 1)
  }
}

/**
 * 跳转到下一题
 */
const goToNextQuestion = () => {
  if (currentQuestionId.value < questions.value.length) {
    switchQuestion(currentQuestionId.value + 1)
  }
}

/**
 * 标记题目为已答
 */
function markAsAnswered(questionId) {
  const question = questions.value.find(q => q.id === questionId)
  if (question) {
    question.answered = true
  }
}

/**
 * 切换提示显示状态（仅在练习模式下可用）
 */
const toggleHint = () => {
  // 只有在练习模式下才能切换提示
  if (examMode === 'practice') {
    showHint.value = !showHint.value
  }
}

// ==================== 答案检查 ====================
/**
 * 检查当前题目的答案是否正确
 */
const isCurrentAnswerCorrect = () => {
  const question = currentQuestion()
  if (!question || !question.answered) return false

  if (question.type === 1) {
    // 单选题
    const selectedOption = question.options.find(opt => opt.label === question.userAnswer)
    return selectedOption ? selectedOption.isCorrect : false
  } else if (question.type === 2) {
    // 多选题
    if (!Array.isArray(question.userAnswer) || question.userAnswer.length === 0) return false

    // 检查用户选择的选项是否都正确，以及是否有遗漏的正确选项
    const selectedOptions = question.options.filter(opt =>
        question.userAnswer.includes(opt.label))

    const correctOptions = question.options.filter(opt => opt.isCorrect)

    // 用户选择的选项数应该等于正确选项数，且每个选择都是正确的
    return selectedOptions.length === correctOptions.length &&
        selectedOptions.every(opt => opt.isCorrect)
  } else if (question.type === 3) {
    // 判断题 - 需要处理"A"/"B"和"1"/"0"两种格式
    let selectedOption = question.options.find(opt => opt.value === question.userAnswer);
    // 如果没找到，尝试使用"A"/"B"格式查找
    if (!selectedOption) {
      if (question.userAnswer === 'A') {
        selectedOption = question.options.find(opt => opt.value === '1');
      } else if (question.userAnswer === 'B') {
        selectedOption = question.options.find(opt => opt.value === '0');
      }
    }
    return selectedOption ? selectedOption.isCorrect : false
  }

  return false
}

/**
 * 检查指定题目的答案是否正确（用于只读模式下的颜色标识）
 */
const isAnswerCorrect = (question) => {
  if (!question.answered) return false;

  if (question.type === 1) {
    // 单选题
    const selectedOption = question.options.find(opt => opt.label === question.userAnswer)
    return selectedOption ? selectedOption.isCorrect : false
  } else if (question.type === 2) {
    // 多选题
    if (!Array.isArray(question.userAnswer) || question.userAnswer.length === 0) return false

    // 检查用户选择的选项是否都正确，以及是否有遗漏的正确选项
    const selectedOptions = question.options.filter(opt =>
        question.userAnswer.includes(opt.label))

    const correctOptions = question.options.filter(opt => opt.isCorrect)

    // 用户选择的选项数应该等于正确选项数，且每个选择都是正确的
    return selectedOptions.length === correctOptions.length &&
        selectedOptions.every(opt => opt.isCorrect)
  } else if (question.type === 3) {
    // 判断题 - 需要处理"A"/"B"和"1"/"0"两种格式
    let selectedOption = question.options.find(opt => opt.value === question.userAnswer);
    // 如果没找到，尝试使用"A"/"B"格式查找
    if (!selectedOption) {
      if (question.userAnswer === 'A') {
        selectedOption = question.options.find(opt => opt.value === '1');
      } else if (question.userAnswer === 'B') {
        selectedOption = question.options.find(opt => opt.value === '0');
      }
    }
    return selectedOption ? selectedOption.isCorrect : false
  }

  return false
}

/**
 * 获取正确答案（只显示选项标签，如A、B、C、D）
 */
const getCorrectAnswer = () => {
  const question = currentQuestion()
  if (!question) return ''

  if (question.type === 1 || question.type === 3) {
    // 单选题和判断题
    const correctOption = question.options.find(opt => opt.isCorrect)
    return correctOption ? correctOption.label : '无正确答案'
  } else if (question.type === 2) {
    // 多选题
    const correctOptions = question.options.filter(opt => opt.isCorrect)
    return correctOptions.map(opt => opt.label).join('; ')
  }

  return ''
}

// ==================== 数据存储 ====================
/**
 * 保存答题记录到本地存储
 */
const saveAnswerRecord = () => {
  // 只在非只读模式下保存
  if (!isReadOnly.value) {
    const record = {
      sessionId: examSessionId.value,
      timestamp: Date.now(),
      questions: questions.value.map(q => {
        // 对于判断题，需要将"1"/"0"转换为"A"/"B"进行存储
        let userAnswer = q.userAnswer;
        if (q.type === 3) {
          if (q.userAnswer === '1') {
            userAnswer = 'A';
          } else if (q.userAnswer === '0') {
            userAnswer = 'B';
          }
        }

        return {
          id: q.id,
          number: q.number,
          type: q.type,
          answered: q.answered,
          userAnswer: userAnswer
        };
      })
    }

    localStorage.setItem('currentExamRecord', JSON.stringify(record))
  }
}

/**
 * 恢复答题记录
 */
const restoreAnswerRecords = () => {
  const recordStr = localStorage.getItem('currentExamRecord')
  if (recordStr) {
    try {
      const record = JSON.parse(recordStr)

      // 检查是否为同一场考试（通过sessionId判断）
      if (record.sessionId === examSessionId.value) {
        // 恢复答题记录
        record.questions.forEach(savedQuestion => {
          const question = questions.value.find(q => q.id === savedQuestion.id || q.number === savedQuestion.number)
          if (question) {
            question.answered = savedQuestion.answered
            question.userAnswer = savedQuestion.userAnswer
          }
        })
      } else {
        // 不是同一场考试，但在只读模式下我们仍然要恢复记录
        if (isReadOnly.value) {
          // 恢复答题记录
          record.questions.forEach(savedQuestion => {
            const question = questions.value.find(q => q.id === savedQuestion.id || q.number === savedQuestion.number)
            if (question) {
              question.answered = savedQuestion.answered
              question.userAnswer = savedQuestion.userAnswer
            }
          })
        } else {
          // 不是同一场考试且不是只读模式，清除旧记录
          localStorage.removeItem('currentExamRecord')
        }
      }

      // 更新当前题目的选项值
      initializeQuestionOptions()
    } catch (e) {
      console.error('恢复答题记录失败:', e)
      localStorage.removeItem('currentExamRecord')
    }
  }
}

/**
 * 更新当前题目的选项值
 */
const updateCurrentQuestionOptions = () => {
  const question = questions.value.find(q => q.id === currentQuestionId.value)
  if (question) {
    if (question.type === 1) {
      singleAnswer.value = question.userAnswer || ''
    } else if (question.type === 2) {
      // 对于多选题，确保multipleAnswers是一个数组
      if (Array.isArray(question.userAnswer)) {
        multipleAnswers.value = question.userAnswer
      } else if (typeof question.userAnswer === 'string' && question.userAnswer) {
        // 如果是字符串形式的答案（如"A;B"），需要分割成数组
        multipleAnswers.value = question.userAnswer.split(';').map(ans => ans.trim()).filter(ans => ans)
      } else {
        multipleAnswers.value = []
      }
    } else if (question.type === 3) {
      // 对于判断题，需要将"A"/"B"转换为"1"/"0"
      if (question.userAnswer === 'A') {
        trueFalseAnswer.value = '1'
      } else if (question.userAnswer === 'B') {
        trueFalseAnswer.value = '0'
      } else {
        trueFalseAnswer.value = question.userAnswer !== undefined && question.userAnswer !== null ?
            String(question.userAnswer) : ''
      }
    }
  }
}

/**
 * 在题目加载完成后初始化选项状态
 */
const initializeQuestionOptions = () => {
  // 使用 nextTick 确保 DOM 更新完成后再设置选项
  nextTick(() => {
    updateCurrentQuestionOptions()
  })
}

// ==================== 考试提交 ====================
/**
 * 交卷功能
 */
const submitPaper = () => {
  // 只读模式下不交卷
  if (isReadOnly.value) return;

  // 确保在交卷前保存最新的考试信息
  saveExamInfo();

  // 记录考试结束时间
  const examEndTime = Date.now()

  // 计算考试耗时（秒）
  const examDuration = Math.floor((examEndTime - examStartTime.value) / 1000)
  // 收集答题结果
  const resultDetails = []
  let correctCount = 0
  let answeredCount = 0

  questions.value.forEach((question, index) => {
    let answer = ''
    let isCorrect = false

    if (question.type === 1) {
      // 单选题答案处理
      if (question.userAnswer) {
        answeredCount++
        // 查找选项标签和文本
        const selectedOption = question.options.find(opt => opt.label === question.userAnswer)
        if (selectedOption) {
          answer = selectedOption.label
          isCorrect = selectedOption.isCorrect
        } else {
          answer = question.userAnswer
        }
      }
    } else if (question.type === 2) {
      // 多选题答案处理
      if (Array.isArray(question.userAnswer) && question.userAnswer.length > 0) {
        answeredCount++
        const answerLabels = question.userAnswer.map(answerLabel => {
          const selectedOption = question.options.find(opt => opt.label === answerLabel)
          return selectedOption ? selectedOption.label : answerLabel
        })
        answer = answerLabels.join('; ')

        // 检查多选题是否正确
        const selectedOptions = question.options.filter(opt =>
            question.userAnswer.includes(opt.label))
        const correctOptions = question.options.filter(opt => opt.isCorrect)
        isCorrect = selectedOptions.length === correctOptions.length &&
            selectedOptions.every(opt => opt.isCorrect)
      }
    } else if (question.type === 3) {
      // 判断题答案处理
      if (question.userAnswer) {
        answeredCount++
        if (question.userAnswer === '1') {
          const selectedOption = question.options.find(opt => opt.value === '1')
          answer = 'A'
          isCorrect = selectedOption ? selectedOption.isCorrect : false
        } else if (question.userAnswer === '0') {
          const selectedOption = question.options.find(opt => opt.value === '0')
          answer = 'B'
          isCorrect = selectedOption ? selectedOption.isCorrect : false
        } else {
          answer = question.userAnswer
        }
      }
    }

    if (isCorrect) {
      correctCount++
    }

    resultDetails.push({
      number: index + 1,
      typeName: question.typeName,
      userAnswer: answer || '未作答',
      answered: !!question.userAnswer,
      isCorrect: isCorrect
    })
  })

  // 根据考试类型计算分数
  let score = 0;

  // 获取考试类型
  const examInfoStr = localStorage.getItem('currentExamInfo');
  let examType = 'exam'; // 默认为正式考试
  if (examInfoStr) {
    try {
      const examInfo = JSON.parse(examInfoStr);
      examType = examInfo.examType || 'exam';
    } catch (e) {
      console.error('解析考试信息失败:', e);
    }
  }

  // 根据不同考试类型使用不同的计分规则
  if (examType === 'exam') {
    // 正式考试：单选题0.5分，多选题1分，判断题0.5分
    questions.value.forEach(question => {
      if (question.answered) {
        const isCorrect = isAnswerCorrect(question);
        if (isCorrect) {
          if (question.type === 1) { // 单选题
            score += 0.5;
          } else if (question.type === 2) { // 多选题
            score += 1;
          } else if (question.type === 3) { // 判断题
            score += 0.5;
          }
        }
      }
    });
    // 转换为百分制
    score = Math.round(score * 100) / 100;
  } else {
    // 其他考试（章节练习、随机练习）：每题1分
    score = questions.value.length > 0 ? Math.round((correctCount / questions.value.length) * 100) : 0;
  }

  // 构造成绩数据
  const resultData = {
    totalQuestions: questions.value.length,
    answeredQuestions: answeredCount,
    correctAnswers: correctCount,
    score: score,
    details: resultDetails,
    examStartTime: examStartTime.value,
    examEndTime: examEndTime,
    examDuration: examDuration
  }

  // 存储结果到 Pinia store
  examResultStore.setResult(resultData)

  // 保存当前考试记录到历史记录中
  saveCurrentExamToHistory(resultData);

  // 清除当前考试记录
  localStorage.removeItem('currentExamRecord')
  localStorage.removeItem('currentExamInfo')

  // 跳转到成绩页面
  router.push({
    path: '/result'
  })
}

/**
 * 保存当前考试记录到历史记录中
 */
const saveCurrentExamToHistory = (resultData) => {
  // 从localStorage获取考试类型信息
  const examInfoStr = localStorage.getItem('currentExamInfo');

  let examInfo = {};
  if (examInfoStr) {
    try {
      examInfo = JSON.parse(examInfoStr);
    } catch (e) {
      console.error('解析考试信息失败:', e);
    }
  }

  // 确定考试类型 - 优先使用examType，其次使用practiceMode，最后使用默认值
  let examType = 'exam'; // 默认为正式考试
  if (examInfo.examType) {
    examType = examInfo.examType;
  } else if (examInfo.practiceMode) {
    examType = examInfo.practiceMode;
  }

  // 从localStorage获取历史记录
  let examHistory = [];
  const historyStr = localStorage.getItem('examHistory');
  if (historyStr) {
    try {
      examHistory = JSON.parse(historyStr);
    } catch (e) {
      console.error('解析历史记录失败:', e);
    }
  }

  // 构造当前考试记录
  const currentRecord = {
    id: Date.now(),
    date: new Date().toLocaleString(),
    totalQuestions: resultData.totalQuestions,
    answeredQuestions: resultData.answeredQuestions,
    unansweredQuestions: resultData.totalQuestions - resultData.answeredQuestions,
    score: resultData.score,
    duration: resultData.examDuration,
    questions: resultData.details,
    examType: examType, // 使用正确的考试类型
    chapter: examInfo.chapter || null, // 章节信息（仅章节练习时有）
    examId: examInfo.examId || null // 随机练习的唯一标识
  }

  // 添加到历史记录开头
  examHistory.unshift(currentRecord)

  // 限制历史记录数量为10条
  if (examHistory.length > 10) {
    examHistory = examHistory.slice(0, 10)
  }

  // 保存到本地存储
  localStorage.setItem('examHistory', JSON.stringify(examHistory))
}
/**
 * 关闭详情视图，返回到成绩页面
 */
const closeDetailView = () => {
  router.push({
    path: '/result'
  })
}

/**
 * 获取题目圆圈的样式类（用于只读模式下区分答题结果）
 */
const getQuestionClass = (question) => {
  // 非只读模式下保持原有逻辑
  if (!isReadOnly.value) {
    if (question.id === currentQuestionId.value) {
      // 当前题目的特殊样式
      return 'active';
    }
    return question.answered ? 'answered' : 'unanswered';
  }

  // 只读模式下的颜色规则
  if (question.id === currentQuestionId.value) {
    // 当前题目始终显示蓝色
    return 'active';
  } else if (!question.answered) {
    // 未作答显示灰色
    return 'unanswered';
  } else if (isAnswerCorrect(question)) {
    // 正确作答显示绿色
    return 'correct';
  } else {
    // 错误作答显示红色
    return 'incorrect';
  }
}

</script>

<template>
  <el-container class="exam-container">
    <el-header class="exam-header">
      <h1>
        考试系统（{{
          examMode === 'exam' ? '考试模式' :
              (route.query.practiceMode === 'chapter' ? `章节练习 - 第${chapter}章` :
               route.query.practiceMode === 'wrong' ? '错题库练习' : '随机练习')
        }}）
      </h1>
      <div>
        <el-button v-if="!isReadOnly" type="primary" @click="submitPaper" class="submit-button">交卷</el-button>
        <el-button v-else type="primary" @click="closeDetailView" class="close-button">关闭</el-button>
      </div>
    </el-header>

    <el-container>
      <!-- 左侧题目编号列表 -->
      <el-aside width="350px" class="sidebar">
        <h3>题目列表 (共{{ questions.length }}题)</h3>

        <el-tabs v-model="activeTab" tab-position="left" class="question-tabs">
          <!-- 单选题 -->
          <el-tab-pane label="单选题" name="single" v-if="questions.filter(q => q.type === 1).length > 0">
            <div class="question-type-info">{{ questions.filter(q => q.type === 1).length }}题</div>
            <el-scrollbar class="question-list">
              <div class="question-grid">
                <div
                    v-for="question in questions.filter(q => q.type === 1)"
                    :key="question.id"
                    :class="[
                    'question-circle',
                    { 'active': question.id === currentQuestionId },
                    getQuestionClass(question)
                  ]"
                    @click="switchQuestion(question.id)"
                >
                  <span class="number">{{ question.number }}</span>
                </div>
              </div>
            </el-scrollbar>
          </el-tab-pane>

          <!-- 多选题 -->
          <el-tab-pane label="多选题" name="multiple" v-if="questions.filter(q => q.type === 2).length > 0">
            <div class="question-type-info">{{ questions.filter(q => q.type === 2).length }}题</div>
            <el-scrollbar class="question-list">
              <div class="question-grid">
                <div
                    v-for="question in questions.filter(q => q.type === 2)"
                    :key="question.id"
                    :class="[
                    'question-circle',
                    { 'active': question.id === currentQuestionId },
                    getQuestionClass(question)
                  ]"
                    @click="switchQuestion(question.id)"
                >
                  <span class="number">{{ question.number }}</span>
                </div>
              </div>
            </el-scrollbar>
          </el-tab-pane>

          <!-- 判断题 -->
          <el-tab-pane label="判断题" name="trueFalse" v-if="questions.filter(q => q.type === 3).length > 0">
            <div class="question-type-info">{{ questions.filter(q => q.type === 3).length }}题</div>
            <el-scrollbar class="question-list">
              <div class="question-grid">
                <div
                    v-for="question in questions.filter(q => q.type === 3)"
                    :key="question.id"
                    :class="[
                    'question-circle',
                    { 'active': question.id === currentQuestionId },
                    getQuestionClass(question)
                  ]"
                    @click="switchQuestion(question.id)"
                >
                  <span class="number">{{ question.number }}</span>
                </div>
              </div>
            </el-scrollbar>
          </el-tab-pane>
        </el-tabs>

        <div class="legend">
          <div class="legend-container">
            <div v-if="!isReadOnly" class="legend-item">
              <div class="legend-color answered-color"></div>
              <span>已答题</span>
            </div>
            <div v-if="!isReadOnly" class="legend-item">
              <div class="legend-color unanswered-color"></div>
              <span>未答题</span>
            </div>
            <div v-if="!isReadOnly" class="legend-item">
              <div class="legend-color active-color"></div>
              <span>当前题</span>
            </div>
            <div v-else class="legend-item">
              <div class="legend-color correct-color"></div>
              <span>正确</span>
            </div>
            <div v-if="isReadOnly" class="legend-item">
              <div class="legend-color incorrect-color"></div>
              <span>错误</span>
            </div>
            <div v-if="isReadOnly" class="legend-item">
              <div class="legend-color unanswered-color"></div>
              <span>未答题</span>
            </div>
          </div>
        </div>
      </el-aside>

      <!-- 主内容区域 -->
      <el-main class="main-content">
        <div v-if="questions.length > 0" class="question-area">
          <div v-if="currentQuestion()" class="question-item">
            <h2>{{ currentQuestion().title }}</h2>
            <p v-html="currentQuestion().content"></p>

            <div v-if="currentQuestion().type === 1">
              <el-radio-group
                  v-model="singleAnswer"
                  class="question-options"
                  :disabled="isReadOnly"
              >
                <el-radio
                    v-for="option in currentQuestion().options"
                    :key="option.id || option.label"
                    :value="option.label"
                >
                  {{ option.label }}. {{ option.text }}
                </el-radio>
              </el-radio-group>
            </div>

            <div v-else-if="currentQuestion().type === 2">
              <el-checkbox-group
                  v-model="multipleAnswers"
                  class="question-options"
                  :disabled="isReadOnly"
              >
                <el-checkbox
                    v-for="option in currentQuestion().options"
                    :key="option.id || option.label"
                    :value="option.label"
                >
                  {{ option.label }}. {{ option.text }}
                </el-checkbox>
              </el-checkbox-group>
            </div>

            <div v-else>
              <el-radio-group
                  v-model="trueFalseAnswer"
                  class="question-options"
                  :disabled="isReadOnly"
              >
                <el-radio
                    v-for="option in currentQuestion().options"
                    :key="option.label"
                    :value="option.value"
                    :disabled="isReadOnly"
                >
                  {{ option.label }}. {{ option.text }}
                </el-radio>
              </el-radio-group>
            </div>

            <!-- 仅在练习模式下显示提示按钮，且不在只读模式下显示 -->
            <el-button
                v-if="examMode === 'practice' && !isReadOnly"
                @click="toggleHint"
                type="warning"
                class="hint-button"
            >
              {{ showHint ? '隐藏提示' : '显示提示' }}
            </el-button>

            <!-- 显示答案提示和解析 -->
            <el-alert
                v-if="(examMode === 'practice' && showHint) || isReadOnly"
                :type="currentQuestion().answered ? (isCurrentAnswerCorrect() ? 'success' : 'error') : 'info'"
                :closable="false"
                class="answer-hint"
            >
              <!-- 非只读模式或只读模式下显示正确答案 -->
              <p><strong>正确答案:</strong> {{ getCorrectAnswer() }}</p>
              <!-- 显示题目解析 -->
              <div v-if="currentQuestion().analysis" class="analysis">
                <p class="analysis-content">{{ currentQuestion().analysis }}</p>
              </div>
            </el-alert>

            <div class="navigation-buttons">
              <el-button
                  @click="goToPreviousQuestion"
                  :disabled="currentQuestionId <= 1"
              >
                上一题
              </el-button>
              <el-button
                  @click="goToNextQuestion"
                  :disabled="currentQuestionId >= questions.length"
              >
                下一题
              </el-button>
            </div>
          </div>
        </div>

        <div v-else class="welcome-message">
          <h2>正在加载题目...</h2>
          <p>请稍候</p>
        </div>
      </el-main>
    </el-container>
  </el-container>
</template>

<style scoped>
.exam-container {
  height: 100vh;
  width: 100%;
  display: flex;
  flex-direction: column;
}

.exam-header {
  background-color: #fff;
  color: #333;
  text-align: center;
  padding: 15px 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  z-index: 100;
  flex-shrink: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.exam-header h1 {
  margin: 0;
  font-size: 24px;
}

.submit-button, .close-button {
  height: 40px;
  font-size: 16px;
}

.sidebar {
  background-color: #f5f5f5;
  padding: 20px 10px;
  border-right: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 70px); /* 减去header高度 */
  overflow-y: auto;
}

.sidebar h3 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #333;
  text-align: center;
  font-size: 16px;
}

.question-tabs {
  flex: 1;
  height: 100%;
}

.question-tabs :deep(.el-tabs__header.is-left) {
  margin-right: 10px;
}

.question-tabs :deep(.el-tabs__content) {
  height: 100%;
}

.question-tabs :deep(.el-tab-pane) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.question-tabs :deep(.el-tabs__item) {
  height: auto;
  line-height: normal;
  padding: 10px 15px;
  writing-mode: vertical-lr;
  text-orientation: mixed;
  white-space: nowrap;
  min-width: 30px;
}

.question-type-info {
  font-size: 12px;
  color: #999;
  margin: 5px 0;
  padding-left: 20px;
}

.question-list {
  flex: 1;
  margin-bottom: 10px;
  max-height: unset;
  height: 100%;
}

.question-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 10px;
  padding: 5px;
}

.question-circle {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
  font-weight: bold;
  margin: 0 auto;
}

.question-circle:hover {
  transform: scale(1.1);
}

.question-circle.active {
  background-color: #409eff;
  color: white;
  border: 2px solid #1a7de0;
}

.question-circle.answered {
  background-color: #f0f9eb;
  color: #67c23a;
  border: 2px solid #67c23a;
}

.question-circle.answered.active {
  background-color: #409eff;
  color: white;
  border: 2px solid #1a7de0;
}

.question-circle.unanswered {
  background-color: #fdf6ec;
  color: #e6a23c;
  border: 2px solid #e6a23c;
}

/* 只读模式下的颜色规则 */
.question-circle.correct {
  background-color: #f0f9eb;
  color: #67c23a;
  border: 2px solid #67c23a;
}

.question-circle.incorrect {
  background-color: #fef0f0;
  color: #f56c6c;
  border: 2px solid #f56c6c;
}

.legend {
  border-top: 1px solid #e4e7ed;
  padding-top: 15px;
  margin-top: auto;
}

.legend-container {
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
}

.legend-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  font-size: 12px;
  margin-right: 15px;
}

.legend-color {
  width: 15px;
  height: 15px;
  border-radius: 3px;
  margin-right: 8px;
}

.answered-color {
  background-color: #f0f9eb;
  border: 1px solid #67c23a;
}

.unanswered-color {
  background-color: #fdf6ec;
  border: 1px solid #e6a23c;
}

.active-color {
  background-color: #409eff;
}

/* 只读模式下的图例 */
.correct-color {
  background-color: #f0f9eb;
  border: 1px solid #67c23a;
}

.incorrect-color {
  background-color: #fef0f0;
  border: 1px solid #f56c6c;
}

.main-content {
  background-color: #fff;
  padding: 20px;
  flex: 1;
  overflow: auto;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  width: 100%;
}

.question-area {
  width: 100%;
  max-width: 800px;
}

.question-item h2 {
  color: #333;
  margin-bottom: 20px;
  font-size: 20px;
}

.question-options {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 30px;
  align-items: flex-start;
}

.question-options :deep(.el-radio) {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  height: auto;
  white-space: normal;
  line-height: normal;
  padding: 10px;
}

.question-options :deep(.el-checkbox) {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  height: auto;
  white-space: normal;
  line-height: normal;
  padding: 10px;
}

.hint-button {
  margin-bottom: 20px;
}

.answer-hint {
  margin-bottom: 20px;
}

.answer-hint p {
  margin: 5px 0;
}

.analysis {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px dashed #ddd;
}

.analysis-title {
  font-weight: bold;
  color: #666;
}

.analysis-content {
  color: #666;
  line-height: 1.6;
}

.navigation-buttons {
  margin-top: 30px;
  display: flex;
  justify-content: space-between;
}

.navigation-buttons :deep(.el-button) {
  width: 100px;
}

.welcome-message {
  text-align: center;
  padding: 50px 20px;
  width: 100%;
}

.welcome-message h2 {
  color: #28a745;
  font-size: 32px;
  margin-bottom: 15px;
}

.welcome-message p {
  font-size: 18px;
  color: #666;
}
</style>